import datetime
from pyecharts import options as opts
from pyecharts.charts import Calendar
import pandas as pd
import numpy as np


class Calendar_flow():
    def __init__(self, dataset, place=0, year='2015'):
        self.paint_data=dataset
        self.place=place #九寨沟——0；四姑娘山——1
        self.year=year

        #主程序入口
        self.main()
    
    
    #主程序入口函数实现
    def main(self):
        
        # 调用获取数据函数
        self.getData()
        # 调用绘图函数
        self.paint()
        
        
    def getData(self):
            
        df = self.paint_data.loc[:,['date', 'flow']] #提取日期和客流数据
        df=df.loc[df['date'].str.contains(self.year)] #筛选指定年份的数据
        # df['flow'] = pd.to_numeric(df['flow'])
        # print(df.dtypes)
        # df['date'] = df['date'].replace('/','-')
        # print(df)
        self.paint_data=df
        # print(self.paint_data)
        
        

    def paint(self):
        date_flow=np.array(self.paint_data)#将dataframe转化为numpy数组
        # 求绘图所需数据
        begin = datetime.date(int(self.year), 1, 1)
        end = datetime.date(int(self.year), 12, 31)
        data = [
            [str(begin + datetime.timedelta(days=i)), date_flow[i,-1]]
            for i in range((end - begin).days + 1)
        ]

        #求最大客流和最小客流
        max_flow=max(date_flow[:,-1].tolist())
        min_flow=min(date_flow[:,-1].tolist())
        # print(min_flow)
        
        # print(data)
        
        if self.place==0:
            title='九寨沟'+self.year+'年客流情况'
        else:
            title='四姑娘山'+self.year+'年客流情况'       
        
        fileName='3.1 (L1400)'+title+"日历图.html"
        
        c = (
            Calendar(init_opts=opts.InitOpts(width="1400px", height="600px"))
            .add(
                "",
                data,
                calendar_opts=opts.CalendarOpts(
                    range_=self.year,
                    daylabel_opts=opts.CalendarDayLabelOpts(name_map="cn"),
                    monthlabel_opts=opts.CalendarMonthLabelOpts(name_map="cn"),
                ),
            )
            .set_global_opts(
                title_opts=opts.TitleOpts(title=title),
                visualmap_opts=opts.VisualMapOpts(
                    max_=max_flow,
                    min_=min_flow,
                    orient="horizontal",
                    is_piecewise=True,
                    pos_top="230px",
                    pos_left="100px",
                ),
            )
            .render('resultFile/'+fileName)
        )
        
        print(fileName+"已生成！")

